package cn.hashq.netpostclient.runner;

import cn.hashq.netpostclient.cache.ConnectionInfo;
import cn.hashq.netpostclient.util.NettyUtil;
import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class ProxyConnectRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<String> serverUrls = args.getOptionValues("proxy-url");
        if (CollUtil.isEmpty(serverUrls) || CollUtil.size(serverUrls) != 1) {
            log.error("proxy-url不能为空,且只能有一个值");
            System.exit(0);
        }
        List<String> secrets = args.getOptionValues("secret");
        if (CollUtil.isEmpty(secrets) || CollUtil.size(secrets) != 1) {
            log.error("secret不能为空,且只能有一个值");
            System.exit(0);
        }
        String serverUrl = serverUrls.get(0);
        String[] serverInfo = serverUrl.split(":");
        if (serverInfo.length != 2) {
            log.error("proxy-url错误");
            System.exit(0);
        }
        String secret = secrets.get(0);
        ConnectionInfo.getInstance().setProxyUrl(serverUrl);
        ConnectionInfo.getInstance().setSecret(secret);
        NettyUtil.connectServer(serverInfo, secret);
    }


}
